package com.lry.sso.controller;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import com.lry.sso.common.entity.response.ResultData;
import com.lry.sso.common.entity.response.Ret;
import com.lry.sso.auth.common.exception.LoginError;
import com.lry.sso.common.exception.SysInvocationException;
import com.lry.sso.common.util.captcha.Captcha;
import com.lry.sso.service.CaptchaService;
import com.lry.sso.service.redis.service.RedisService;

import com.lry.sso.service.vo.CaptchaVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 验证码
 *
 * @author 李瑞益
 * @date 2019/9/4
 */
@RestController
@RequestMapping("sso/login/v1")
public class CaptchaController {

    private static Logger logger = LoggerFactory.getLogger(CaptchaController.class);

    @Autowired
    private RedisService redisService;

    @Autowired
    private CaptchaService captchaService;

    /**
     * 验证码
     */
    @GetMapping("/captcha")
    public ResultData<Map<String,String>> captcha(){
        Captcha captcha = captchaService.getAndSaveCaptcha();
        if (captcha == null) {
            logger.error("验证码生成失败");
            throw new SysInvocationException(LoginError.CAPTCHA_CREATE);
        }
        Base64.Encoder encoder = Base64.getEncoder();
        Map<String,String> result = new HashMap<>();
        result.put("pic",encoder.encodeToString(captcha.getImg()));
        result.put("captchaId",captcha.getCaptchasId());
        return Ret.data(result);
    }

    /**
     * 验证验证码
     * @return 验证结果
     */
    @PostMapping("/captcha/validate")
    public ResultData checkVerifyCode(@RequestBody CaptchaVo captchaVo) {
        if (captchaVo == null) {
            throw new SysInvocationException(LoginError.CAPTCHA_ERROR);
        }
        if (!captchaService.validCaptcha(captchaVo.getCaptchaId(),captchaVo.getCaptcha())) {
            redisService.delete(captchaVo.getCaptchaId());
            return Ret.data(false);
        }
        return Ret.data(true);
    }
}
